<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkRoom\Action\Sidebar;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactRoomContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 客户画像-客户群员工.
 *
 * Class RoomEmployee
 * @Controller
 */
class EmployeeIndex extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkContactRoomContract
     */
    protected $workContactRoom;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployee;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/workRoom/employeeIndex", methods="get")
     */
    public function handle(): array
    {
        $user = user();
        # # 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 接收参数
        $params = [
            'id' => (int) $this->request->input('id'),
            'name' => $this->request->input('name', ''),
        ];
        // 校验参数
        $this->validated($params);
        $employeeIds = $this->workContactRoom->getWorkContactRoomsByRoomIdEmployee($params['id'], ['employee_id']);
        if (empty($params['name'])) {
            $employees = $this->workEmployee->getWorkEmployeesById(array_column($employeeIds, 'employeeId'), ['id', 'name', 'avatar']);
        } else {
            $employees = $this->workEmployee->getWorkEmployeesByIdName(array_column($employeeIds, 'employeeId'), $params['name'], ['id', 'name', 'avatar']);
        }
        # # 头像处理
        foreach ($employees as $k => $v) {
            $employees[$k]['avatar'] = file_full_url($v['avatar']);
        }
        return $employees;
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'id' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'id.required' => 'id 必传',
        ];
    }
}
